package com.outsourcing.bottle.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.Date;
import java.util.HashMap;

import oauth.facebook.AsyncFacebookRunner;
import oauth.facebook.BaseRequestListener;
import oauth.facebook.DialogError;
import oauth.facebook.Facebook;
import oauth.facebook.Facebook.DialogListener;
import oauth.facebook.FacebookError;
import oauth.facebook.SessionEvents;
import oauth.facebook.SessionEvents.AuthListener;
import oauth.facebook.Util;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aviary.android.feather.Constants;
import com.aviary.android.feather.FeatherActivity;
import com.aviary.android.feather.library.media.ExifInterfaceWrapper;
import com.aviary.android.feather.library.moa.MoaHD;
import com.aviary.android.feather.library.moa.MoaHD.Error;
import com.aviary.android.feather.library.providers.FeatherContentProvider;
import com.aviary.android.feather.library.providers.FeatherContentProvider.ActionsDbColumns.Action;
import com.aviary.android.feather.library.utils.IOUtils;
import com.aviary.android.feather.library.utils.StringUtils;
import com.aviary.android.feather.library.utils.SystemUtils;
import com.google.gson.Gson;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.db.BottleTypeTable;
import com.outsourcing.bottle.db.LoginUserInfoTable;
import com.outsourcing.bottle.db.OtherConfigTable;
import com.outsourcing.bottle.db.PlatformAccountTable;
import com.outsourcing.bottle.domain.BottleTypeEntry;
import com.outsourcing.bottle.domain.LocationEntry;
import com.outsourcing.bottle.domain.LoginUserInfo;
import com.outsourcing.bottle.domain.LoginUserInfoEntry;
import com.outsourcing.bottle.domain.OtherConfigEntry;
import com.outsourcing.bottle.domain.PlatformAccount;
import com.outsourcing.bottle.domain.PlatformBindConfig;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.oauth.OAuth;
import com.outsourcing.bottle.ui.fragment.BottleFragment;
import com.outsourcing.bottle.ui.fragment.ExchangeFragment;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BasicUIEvent;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.ImageThumbnail;
import com.outsourcing.bottle.util.SubmitTask;
import com.outsourcing.bottle.util.UICore;
import com.outsourcing.bottle.util.Utility;

/**
 * 
 * @author 06peng
 * 
 */
public class ExpandEditActivity extends BasicActivity implements BasicUIEvent, OnClickListener, Callback {

	public final int init_loginuser_info = 1;
	public final int activity_result_camara_with_data = 1006;
	public final int activity_result_pick_with_data = 1008;
	public final int activity_result_cropimage_with_data = 1007;
	public final int activity_result_aviary_with_data = 1009;
	public final int send_bt = 4;
	public final int send_bt_error = 5;
	public final int send_bt_success = 6;
	public final int locate = 7;
	public final int do_success = 8;
	public final int error = 9;
	public final int replay_bt = 10;
	public final int copy_mauaul_bt = 11;
	public final int transmit_bt = 12;
	public final int reply_infoex = 13;
	public final int apply_picex = 14;
	public final int reply_picex = 15;
	public final int replypic_picex = 16;
	public final int forwardpic_picex = 17;
	public final int reply_photo = 18;
	public final int reply_comment = 19;
	public final int apply_friend = 20;
	public final int send_message = 21;
	public final int add_album = 22;
	public final int edit_album = 23;
	public final int upload_photo = 24;
	public final int edit_memo = 25;
	public final int set_doing = 26;
	public final int edit_photo = 27;
	
	public final int forward_bt = 36;
	public final int forward_photo = 37;
	public final int paint_bt = 38;
	public final int paint_picex = 39;
	public final int paint_photo = 40;
	
	private final int oauth_tritter = 28;
	private final int oauth_facebook = 29;
	private final int oauth_weibo = 30;
	private final int oauth_tencent = 31;
	private final int oauth_renren = 32;
	private final int oauth_douban = 33;
	private final int oauth_qq = 34;
	public static final int oauth_bind = 35;

	private ImageView backView;
	private TextView titleView;
	private ImageButton confirmView;
	private ImageView lockView;
	private ImageView locateView;
	private TextView locationView;
	private EditText editView;
	private ImageView uploadpicView;
	private ImageView twitterView;
	private ImageView facebookView;
	private ImageView weiboView;
	private ImageView tentcentView;
	private ImageView doubanView;
	private ImageView renrenView;
	private ImageView qqView;
	private LinearLayout platformLayout;
	private RelativeLayout updatepicLayout;
	private LinearLayout locateLayout;

	private Bundle bundle;
	private String fromType;
	private int bttype_id;
	private String fuids;
	private double bt_geo_lng;
	private double bt_geo_lat;
	private String bt_geo_reference;
	private BottleTypeEntry entry;
	private LoginUserInfoEntry userEntry;
	/** 回应资料交换:apply发起资料交换; reply回应资料交换 */
	private String reply_infoex_type;

	/** 回应照片交换:reply回应照片交换; accept接受照片交换两个功能。 */
	private String reply_picex_type;
	private int ouid;
	public int picid;
	private int pic_uid;
	private int fuid;
	private int commentid;
	public int albumid;
	private String albumname;
	private String photoname;
	private String memo;
	/** 上传照片 的来源页面 album相册上传；photos相册查看上传；photo_detail相片查看上传 */
	private String upload_from;
	/** 编辑相册的来源页面 ablum、photos */
	private String album_from;

	private boolean bind_twitter;
	private boolean bind_facebook;
	private boolean bind_weibo;
	private boolean bind_tencent;
	private boolean bind_douban;
	private boolean bind_renren;
	private boolean bind_qq;
	private boolean isLock;
	public OAuth oauth;
	private String platform;
	public static final String CALLBACKURL = "app:authorize";
	private boolean isGoOAuth;

	private File picFile;
	private Uri photoUri;
	private boolean hasImage;
	private final static int REQUEST_WIDTH = 1000;
	private WeakReference<Bitmap> bitmapWeak;

	private LocationEntry myLocation;
	private boolean isLocate;
	private OtherConfigEntry ocEntry;

	static final int targetBytes = 65000;
	static final int targetShortSide = 400;
	static final int targetLongSide = 480;
	private static final String TAG = ExpandEditActivity.class.getSimpleName();

	private boolean isNeedUpdate = false;
	private String return_type = "";
	private Handler handler;
	
	private Facebook mFacebook;
	private AsyncFacebookRunner mAsyncRunner;
	private SessionListener mSessionListener = new SessionListener();
	 
	private String mSessionId = null;
	
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.expand_edit);
		handler = new Handler(this);
		if (ocEntry == null) {
			OtherConfigTable ot = new OtherConfigTable(this);
			ocEntry = ot.getBottleOtherConfig();
		}
		bundle = getIntent().getExtras();
		if (bundle != null) {
			fromType = bundle.getString("from_type");
			initBottleLocation(bundle);
			if (entry == null) {
				BottleTypeTable btt = new BottleTypeTable(this);
				entry = btt.getBottleType(bttype_id);
			}
			if (userEntry == null) {
				LoginUserInfoTable userTable = new LoginUserInfoTable(this);
				userEntry = userTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid());
			}
			initWidget();
			if (fromType.equals(AppContext.SEND_BT)) {
				initSendBt();
			} else if (fromType.equals(AppContext.REPLY_BT)) {
				initReplayBottle();
			} else if (fromType.equals(AppContext.COPYMANUAL_BT)) {
				initCopyMaunalBottle();
			} else if (fromType.equals(AppContext.TRANSMIT_BT)) {
				initTransmitBottle();
			} else if (fromType.equals(AppContext.REPLY_INFOEX)) {
				/** 回应资料交换:apply发起资料交换; replay回应资料交换 */
				reply_infoex_type = bundle.getString("reply_infoex_type");
				initReplayInfoex();
			} else if (fromType.equals(AppContext.APPLY_PICEX)) {
				initApplyPicx();
			} else if (fromType.equals(AppContext.REPLY_PICEX)) {
				reply_picex_type = bundle.getString("reply_picex_type");
				initReplayPicx();
			} else if (fromType.equals(AppContext.REPLYPIC_PICEX)) {
				initReplyPicPicex();
			} else if (fromType.equals(AppContext.FORWARPIC_PICEX)) {
				initForwardPicPicex();
			} else if (fromType.equals(AppContext.REPLY_PHOTO)) {
				initReplyPhoto();
			} else if (fromType.equals(AppContext.REPLY_COMMENT)) {
				initReplyComment();
			} else if (fromType.equals(AppContext.APPLY_FRIEND)) {
				initApplyFriend();
			} else if (fromType.equals(AppContext.SEND_MESSAGE)) {
				initSendMessage();
			} else if (fromType.equals(AppContext.ADD_ALBUM)) {
				initAddAlbum();
			} else if (fromType.equals(AppContext.EDIT_ALBUM)) {
				initEditAlbum();
			} else if (fromType.equals(AppContext.UPLOAD_PHOTO)) {
				initUploadPhoto();
			} else if (fromType.equals(AppContext.EDIT_PHOTO)) {
				initEditPhoto();
			} else if (fromType.equals(AppContext.EDIT_MEMO)) {
				initEditMemo();
			} else if (fromType.equals(AppContext.SET_DOING)) {
				initDoing();
			} else if (fromType.equals(AppContext.PAINT_BT)) {
				initPaintBt();
			} else if (fromType.equals(AppContext.PAINT_PICEX)) {
				initPaintPicex();
			} else if (fromType.equals(AppContext.PAINT_PHOTO)) {
				initPaintPhoto();
			} else if (fromType.equals(AppContext.FORWARD_PHOTO)) {
				initForwardPhoto();
			} else if (fromType.equals(AppContext.FORWARD_BT)) {
				initForwardBt();
			}
		}
	}

	private void initWidget() {
		backView = (ImageView) findViewById(R.id.topbar_back);
		backView.setOnClickListener(this);
		titleView = (TextView) findViewById(R.id.topbar_title);
		confirmView = (ImageButton) findViewById(R.id.topbar_confirm);
		confirmView.setOnClickListener(this);
		lockView = (ImageView) findViewById(R.id.expand_lock);
		lockView.setOnClickListener(this);
		locateView = (ImageView) findViewById(R.id.expand_locate);
		locationView = (TextView) findViewById(R.id.expand_location);
		locateLayout = (LinearLayout) findViewById(R.id.expand_locate_layout);
		locateLayout.setOnClickListener(this);
		uploadpicView = (ImageView) findViewById(R.id.uploadpic);
		uploadpicView.setOnClickListener(this);
		twitterView = (ImageView) findViewById(R.id.expand_twitter);
		twitterView.setOnClickListener(this);
		facebookView = (ImageView) findViewById(R.id.expand_facebook);
		facebookView.setOnClickListener(this);
		weiboView = (ImageView) findViewById(R.id.expand_weibo);
		weiboView.setOnClickListener(this);
		tentcentView = (ImageView) findViewById(R.id.expand_tencent);
		tentcentView.setOnClickListener(this);
		doubanView = (ImageView) findViewById(R.id.expand_douban);
		doubanView.setOnClickListener(this);
		renrenView = (ImageView) findViewById(R.id.expand_renren);
		renrenView.setOnClickListener(this);
		qqView = (ImageView) findViewById(R.id.expand_qq);
		qqView.setOnClickListener(this);
		editView = (EditText) findViewById(R.id.expand_edit);
		platformLayout = (LinearLayout) findViewById(R.id.platform_layout);
		updatepicLayout = (RelativeLayout) findViewById(R.id.uploadpic_layout);
		if (userEntry == null) {
			return;
		}
		if (userEntry.getTwitterok() == 1) {
			bind_twitter = true;
			twitterView.setBackgroundResource(R.drawable.edit_ico_twitter);
		}
		if (userEntry.getFacebookok() == 1) {
			bind_facebook = true;
			facebookView.setBackgroundResource(R.drawable.edit_ico_facebook);
		}
		if (userEntry.getDoubanok() == 1) {
			bind_douban = true;
			doubanView.setBackgroundResource(R.drawable.edit_ico_douban);
		}
		if (userEntry.getQqok() == 1) {
			bind_qq = true;
			qqView.setBackgroundResource(R.drawable.edit_ico_qq);
		}
		if (userEntry.getTqqok() == 1) {
			bind_tencent = true;
			tentcentView.setBackgroundResource(R.drawable.edit_ico_tqq);
		}
		if (userEntry.getSinaok() == 1) {
			bind_weibo = true;
			weiboView.setBackgroundResource(R.drawable.edit_ico_weibo);
		}
		if (userEntry.getRenrenok() == 1) {
			bind_renren = true;
			renrenView.setBackgroundResource(R.drawable.edit_ico_renren);
		}
		
		editView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
					confirm();
				}
				return false;
			}
		});
	}

	private void initBottleLocation(Bundle bundle) {
		bttype_id = bundle.getInt("bttype_id");
		bt_geo_lng = bundle.getDouble("bt_geo_lng", 0);
		bt_geo_lat = bundle.getDouble("bt_geo_lat", 0);
		bt_geo_reference = bundle.getString("bt_geo_reference");
	}
	
	private void initLocateTextView() {
		if (AppContext.auto_locate) {
			//网络定位
			networkLocat();
			locationView.setText("正在定位中...");
		}
	}

	private void initReplayBottle() {
		bttype_id = bundle.getInt("bttype_id");
		return_type = bundle.getString("return_type");
		titleView.setText(getString(R.string.expand_edit_title_reply_bt));
		locateView.setVisibility(View.VISIBLE);
		locationView.setVisibility(View.VISIBLE);
		platformLayout.setVisibility(View.GONE);
		updatepicLayout.setVisibility(View.VISIBLE);
		initLocateTextView();
	}

	private void initSendBt() {
		if (entry.getBttype_pic_show() == 1) {
			uploadpicView.setVisibility(View.VISIBLE);
		} else {
			uploadpicView.setVisibility(View.GONE);
		}
		if (entry.getBttype_spread_show() == 1) {
			platformLayout.setVisibility(View.VISIBLE);
		} else {
			platformLayout.setVisibility(View.GONE);
		}
		String bottlename = null;
		if (AppContext.language == 1) {
			bottlename = entry.getBttype_name_cn();
		} else {
			bottlename = entry.getBttype_name_en();
		}
		titleView.setText(getString(R.string.expand_edit_sendbt_title1) + " "+ bottlename);
		if (AppContext.language == 1) {
			editView.setHint(entry.getBttype_tips_cn());
		} else {
			editView.setHint(entry.getBttype_tips_en());
		}
		locateView.setVisibility(View.GONE);
		locationView.setVisibility(View.GONE);
		updatepicLayout.setVisibility(View.VISIBLE);
	}

	private void initCopyMaunalBottle() {
		bttype_id = bundle.getInt("bttype_id");
		return_type = bundle.getString("return_type");
		titleView.setText(getString(R.string.expand_edit_title_copymanual_bt));
		editView.setHint(getString(R.string.expand_edit_tips_copymanual_bt));
		locateView.setVisibility(View.GONE);
		locationView.setVisibility(View.GONE);
		platformLayout.setVisibility(View.GONE);
		updatepicLayout.setVisibility(View.GONE);
	}

	private void initTransmitBottle() {
		bttype_id = bundle.getInt("bttype_id");
		titleView.setText(getString(R.string.expand_edit_title_transmit_bt));
		editView.setHint(getString(R.string.expand_edit_tips_transmit_bt));
		locateView.setVisibility(View.GONE);
		locationView.setVisibility(View.GONE);
		platformLayout.setVisibility(View.VISIBLE);
		updatepicLayout.setVisibility(View.GONE);
	}

	private void initForwardBt(){
		bttype_id = bundle.getInt("bttype_id");
		fuids = bundle.getString("fuids");
		return_type = bundle.getString("return_type");
		titleView.setText(getString(R.string.expand_edit_title_forward_bt));
		editView.setHint(getString(R.string.expand_edit_tips_forward_bt));
		locateView.setVisibility(View.GONE);
		locationView.setVisibility(View.GONE);
		platformLayout.setVisibility(View.GONE);
		updatepicLayout.setVisibility(View.GONE);
		locateLayout.setVisibility(View.GONE);
	}
	
	private void initReplayInfoex() {
		ouid = bundle.getInt("ouid");
		platformLayout.setVisibility(View.GONE);
		updatepicLayout.setVisibility(View.GONE);
		locateView.setVisibility(View.VISIBLE);
		locationView.setVisibility(View.VISIBLE);
		if (reply_infoex_type.equals("apply")) {
			titleView.setText(getString(R.string.expand_edit_title_reply_infoex));
			editView.setHint(getString(R.string.expand_edit_tips_reply_infoex));
		} else {
			titleView.setText(getString(R.string.expand_edit_title_replay));
		}
		initLocateTextView();
	}

	private void initApplyPicx() {
		ouid = bundle.getInt("ouid");
		updatepicLayout.setVisibility(View.VISIBLE);
		locateView.setVisibility(View.VISIBLE);
		locationView.setVisibility(View.VISIBLE);
		platformLayout.setVisibility(View.GONE);
		titleView.setText(getString(R.string.expand_edit_title_apply_picex));
		editView.setHint(getString(R.string.expand_edit_tips_reply_infoex2));

		initLocateTextView();
	}

	private void initReplayPicx() {
		ouid = bundle.getInt("ouid");
		if (reply_picex_type.equals("reply")) {
			titleView.setText(getString(R.string.expand_edit_title_replay));
		} else {
			titleView.setText(getString(R.string.expand_edit_title_apply_picex));
			editView.setHint(getString(R.string.expand_edit_tips_reply_photo));
		}
		updatepicLayout.setVisibility(View.VISIBLE);
		locateView.setVisibility(View.VISIBLE);
		locationView.setVisibility(View.VISIBLE);
		platformLayout.setVisibility(View.GONE);

		initLocateTextView();
	}

	private void initReplyPicPicex() {
		ouid = bundle.getInt("ouid");
		picid = bundle.getInt("picid");
		titleView.setText(getString(R.string.expand_edit_title_replay));
		updatepicLayout.setVisibility(View.GONE);
		locateView.setVisibility(View.VISIBLE);
		locationView.setVisibility(View.VISIBLE);
		platformLayout.setVisibility(View.GONE);

		initLocateTextView();
	}

	private void initForwardPicPicex() {
		picid = bundle.getInt("picid");
		pic_uid = bundle.getInt("pic_uid");
		fuid = bundle.getInt("fuid");
		return_type = bundle.getString("return_type");
		titleView.setText(getString(R.string.expand_edit_title_replay));
		editView.setHint(getString(R.string.expand_edit_tips_reply_tofriend));
		updatepicLayout.setVisibility(View.GONE);
		locateView.setVisibility(View.VISIBLE);
		locationView.setVisibility(View.VISIBLE);
		platformLayout.setVisibility(View.GONE);

		initLocateTextView();
	}

	private void initReplyPhoto() {
		picid = bundle.getInt("picid");
		titleView.setText(getString(R.string.expand_edit_title_replay));
		updatepicLayout.setVisibility(View.GONE);
		locateView.setVisibility(View.VISIBLE);
		locationView.setVisibility(View.VISIBLE);
		platformLayout.setVisibility(View.GONE);

		initLocateTextView();
	}

	private void initReplyComment() {
		commentid = bundle.getInt("commentid");
		return_type = bundle.getString("return_type");
		titleView.setText(getString(R.string.expand_edit_tips_reply_commen));
		updatepicLayout.setVisibility(View.GONE);
		locateView.setVisibility(View.VISIBLE);
		locationView.setVisibility(View.VISIBLE);
		platformLayout.setVisibility(View.GONE);

		initLocateTextView();
	}

	private void initApplyFriend() {
		ouid = bundle.getInt("ouid");
		titleView.setText(getString(R.string.expand_edit_tips_apply_friend));
		editView.setHint(getString(R.string.expand_edit_tips_reply_infoex));
		updatepicLayout.setVisibility(View.GONE);
		locateView.setVisibility(View.VISIBLE);
		locationView.setVisibility(View.VISIBLE);
		platformLayout.setVisibility(View.GONE);

		initLocateTextView();
	}

	private void initSendMessage() {
		ouid = bundle.getInt("ouid");
		titleView.setText(getString(R.string.expand_edit_tips_send_message));
		updatepicLayout.setVisibility(View.GONE);
		locateView.setVisibility(View.VISIBLE);
		locationView.setVisibility(View.VISIBLE);
		platformLayout.setVisibility(View.GONE);

		initLocateTextView();
	}

	private void initAddAlbum() {
		titleView.setText(getString(R.string.expand_edit_title_add_album));
		editView.setHint(getString(R.string.expand_edit_tips_add_album));
		updatepicLayout.setVisibility(View.GONE);
		locateView.setVisibility(View.GONE);
		locationView.setVisibility(View.GONE);
		platformLayout.setVisibility(View.GONE);
	}

	private void initEditAlbum() {
		albumid = bundle.getInt("albumid");
		albumname = bundle.getString("albumname");
		album_from = bundle.getString("album_from");
		titleView.setText(getString(R.string.expand_edit_title_edit_album));
		editView.setText(albumname);
		updatepicLayout.setVisibility(View.GONE);
		locateView.setVisibility(View.GONE);
		locationView.setVisibility(View.GONE);
		platformLayout.setVisibility(View.GONE);
	}

	private void initUploadPhoto() {
		albumid = bundle.getInt("albumid");
		ouid = bundle.getInt("ouid");
		upload_from = bundle.getString("upload_from");
		titleView.setText(getString(R.string.expand_edit_title_upload_photo));
		editView.setHint(getString(R.string.expand_edit_tips_upload_photo));
		updatepicLayout.setVisibility(View.VISIBLE);
		locateView.setVisibility(View.VISIBLE);
		locationView.setVisibility(View.VISIBLE);
		platformLayout.setVisibility(View.GONE);

		initLocateTextView();
	}

	private void initEditPhoto() {
		picid = bundle.getInt("picid");
		photoname = bundle.getString("photoname");
		titleView.setText(getString(R.string.expand_edit_title_edit_photo));
		editView.setText(photoname);
		updatepicLayout.setVisibility(View.GONE);
		locateView.setVisibility(View.GONE);
		locationView.setVisibility(View.GONE);
		platformLayout.setVisibility(View.GONE);
	}

	private void initEditMemo() {
		ouid = bundle.getInt("ouid");
		memo = bundle.getString("memo");
		titleView.setText(getString(R.string.expand_edit_title_edit_memo));
		editView.setText(memo);
		updatepicLayout.setVisibility(View.GONE);
		locateView.setVisibility(View.GONE);
		locationView.setVisibility(View.GONE);
		platformLayout.setVisibility(View.GONE);
	}

	private void initDoing() {
		titleView.setText(getString(R.string.expand_edit_title_setmood));
		editView.setHint(getString(R.string.expand_edit_tips_setmood));
		updatepicLayout.setVisibility(View.GONE);
		locateView.setVisibility(View.GONE);
		locationView.setVisibility(View.GONE);
		platformLayout.setVisibility(View.GONE);
	}
	
	private void initForwardPhoto(){
		picid = bundle.getInt("picid");
		return_type = bundle.getString("return_type");
		titleView.setText(getString(R.string.expand_edit_title_forward_photo));
		editView.setHint(getString(R.string.expand_edit_tips_forward_photo));
		locateView.setVisibility(View.GONE);
		locationView.setVisibility(View.GONE);
		platformLayout.setVisibility(View.VISIBLE);
		updatepicLayout.setVisibility(View.GONE);
	}

	private void initPaintBt(){
		return_type = bundle.getString("return_type");
		bttype_id = bundle.getInt("bttype_id");
		titleView.setText(getString(R.string.expand_edit_title_paint_bt));
		locateView.setVisibility(View.VISIBLE);
		locationView.setVisibility(View.VISIBLE);
		platformLayout.setVisibility(View.VISIBLE);
		updatepicLayout.setVisibility(View.GONE);
		uploadpicView.setVisibility(View.GONE);

		File pictureFileDir = new File(
				Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
		picFile = new File(pictureFileDir, "upload.jpeg");
	}
	
	private void initPaintPicex(){
		ouid = bundle.getInt("ouid");
		picid = bundle.getInt("picid");
		return_type = bundle.getString("return_type");
		titleView.setText(getString(R.string.expand_edit_title_paint_bt));
		locateView.setVisibility(View.VISIBLE);
		locationView.setVisibility(View.VISIBLE);
		platformLayout.setVisibility(View.VISIBLE);
		updatepicLayout.setVisibility(View.GONE);
	
		uploadpicView.setVisibility(View.GONE);
		File pictureFileDir = new File(
				Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
		picFile = new File(pictureFileDir, "upload.jpeg");
	
	}
	
	private void initPaintPhoto(){
		picid = bundle.getInt("picid");
		titleView.setText(getString(R.string.expand_edit_title_paint_bt));
		locateView.setVisibility(View.VISIBLE);
		locationView.setVisibility(View.VISIBLE);
		platformLayout.setVisibility(View.VISIBLE);
		updatepicLayout.setVisibility(View.GONE);
	
		uploadpicView.setVisibility(View.GONE);
		File pictureFileDir = new File(
				Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
		picFile = new File(pictureFileDir, "upload.jpeg");
	}
	
	@Override
	public void onClick(View v) {
		if (v == backView) {
			AppContext.getInstance().setFromBottleTime(false);
			AppContext.getInstance().setFromExchangeTime(false);
			finish();
		} else if (v == lockView) {
			if (isLock) {
				isLock = false;
				lockView.setBackgroundResource(R.drawable.unlock);
			} else {
				isLock = true;
				lockView.setBackgroundResource(R.drawable.lock);
				bind_twitter = false;
				twitterView.setBackgroundResource(R.drawable.edit_ico_twitter_gray);
				bind_facebook = false;
				facebookView.setBackgroundResource(R.drawable.edit_ico_facebook_gray);
				bind_weibo = false;
				weiboView.setBackgroundResource(R.drawable.edit_ico_weibo_gray);
				bind_tencent = false;
				tentcentView.setBackgroundResource(R.drawable.edit_ico_tqq_gray);
				bind_douban = false;
				doubanView.setBackgroundResource(R.drawable.edit_ico_douban_gray);
				bind_renren = false;
				renrenView.setBackgroundResource(R.drawable.edit_ico_renren_gray);
				bind_qq = false;
				qqView.setBackgroundResource(R.drawable.edit_ico_qq_gray);
			}
		} else if (v == twitterView) {
			if (isLock) {
				return;
			}
			if (ocEntry.getTwitter_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			if (userEntry.getTwitterok() == 1) {
				if (bind_twitter) {
					bind_twitter = false;
					twitterView.setBackgroundResource(R.drawable.edit_ico_twitter_gray);
				} else {
					bind_twitter = true;
					twitterView.setBackgroundResource(R.drawable.edit_ico_twitter);
				}
			} else {
				UICore.eventTask(this, this, oauth_tritter, "", null);
			}

		} else if (v == facebookView) {
			if (isLock) {
				return;
			}
			if (ocEntry.getFacebook_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			if (userEntry.getFacebookok() == 1) {
				if (bind_facebook) {
					bind_facebook = false;
					facebookView.setBackgroundResource(R.drawable.edit_ico_facebook_gray);
				} else {
					bind_facebook = true;
					facebookView.setBackgroundResource(R.drawable.edit_ico_facebook);
				}
			} else {
				isGoOAuth = true;
				platform = PlatformBindConfig.Facebook;
				mFacebook = new Facebook(PlatformBindConfig.Facebook_AppID);
				mAsyncRunner = new AsyncFacebookRunner(mFacebook);
				SessionEvents.addAuthListener(new SampleAuthListener());
				SessionEvents.addAuthListener(mSessionListener);
				mFacebook.authorize((BasicActivity) AppContext.getContext(), new String[] {}, new LoginDialogListener());
//				UICore.eventTask(this, this, oauth_facebook, "", null);
			}
		} else if (v == weiboView) {
			if (isLock) {
				return;
			}
			if (ocEntry.getWeibo_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			if (userEntry.getSinaok() == 1) {
				if (bind_weibo) {
					bind_weibo = false;
					weiboView.setBackgroundResource(R.drawable.edit_ico_weibo_gray);
				} else {
					bind_weibo = true;
					weiboView.setBackgroundResource(R.drawable.edit_ico_weibo);
				}
			} else {
				UICore.eventTask(this, this, oauth_weibo, "", null);
			}
		} else if (v == tentcentView) {
			if (isLock) {
				return;
			}
			if (ocEntry.getTencent_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			if (userEntry.getTqqok() == 1) {
				if (bind_tencent) {
					bind_tencent = false;
					tentcentView.setBackgroundResource(R.drawable.edit_ico_tqq_gray);
				} else {
					bind_tencent = true;
					tentcentView.setBackgroundResource(R.drawable.edit_ico_tqq);
				}
			} else {
				UICore.eventTask(this, this, oauth_tencent, "", null);
			}
		} else if (v == doubanView) {
			if (isLock) {
				return;
			}
			if (ocEntry.getDouban_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			if (userEntry.getDoubanok() == 1) {
				if (bind_douban) {
					bind_douban = false;
					doubanView.setBackgroundResource(R.drawable.edit_ico_douban_gray);
				} else {
					bind_douban = true;
					doubanView.setBackgroundResource(R.drawable.edit_ico_douban);
				}
			} else {
				UICore.eventTask(this, this, oauth_douban, "", null);
			}
		} else if (v == renrenView) {
			if (isLock) {
				return;
			}
			if (ocEntry.getRenren_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			if (userEntry.getRenrenok() == 1) {
				if (bind_renren) {
					bind_renren = false;
					renrenView.setBackgroundResource(R.drawable.edit_ico_renren_gray);
				} else {
					bind_renren = true;
					renrenView.setBackgroundResource(R.drawable.edit_ico_renren);
				}
			} else {
				UICore.eventTask(this, this, oauth_renren, "", null);
			}
		} else if (v == qqView) {
			if (isLock) {
				return;
			}
			if (ocEntry.getQq_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			if (userEntry.getQqok() == 1) {
				if (bind_qq) {
					bind_qq = false;
					qqView.setBackgroundResource(R.drawable.edit_ico_qq_gray);
				} else {
					bind_qq = true;
					qqView.setBackgroundResource(R.drawable.edit_ico_qq);
				}
			} else {
				UICore.eventTask(this, this, oauth_qq, "", null);
			}
		} else if (v == locateLayout) {
			if (isLock) {
				return;
			}
			if (isLocate) {
				locateView.setBackgroundResource(R.drawable.locate_gray);
				locationView.setText("");
				isLocate = false;
				AppContext.auto_locate = false;
			} else {
				AppContext.auto_locate = true;
				initLocateTextView();
//				UICore.eventTask(this, this, locate, "locate", null);
			}
		} else if (v == uploadpicView) {
			doPickPhotoAction();
		} else if (v == confirmView) {
			confirm();
		}

	}
	
	private void confirm() {
		isNeedUpdate = true;
		if (editView.getText().toString().trim().equals("")) {
			isNeedUpdate = false;
			onToast(getString(R.string.expand_edit_comment_must));
			return;
		} else if (editView.getText().toString().length() < 2) {
			isNeedUpdate = false;
			onToast(getString(R.string.expand_edit_comment_error));
			return;
		}
		if (fromType.equals(AppContext.SEND_BT)) { // 扔瓶子
			if (entry.getBttype_pic_must() == 1) {
				if (!hasImage) {
					onToast(getString(R.string.expand_edit_pic_must));
					return;
				}
			}
			sendBt();
		} else if (fromType.equals(AppContext.REPLY_BT)) { // 回复瓶子
			replay_bt();
		} else if (fromType.equals(AppContext.COPYMANUAL_BT)) {// 手动传递瓶子
			copymanual_bt();
		} else if (fromType.equals(AppContext.TRANSMIT_BT)) { // 转发瓶子
			if (bind_douban || bind_facebook || bind_qq || bind_renren
					|| bind_tencent || bind_twitter || bind_weibo) {
				transmitBt();
			} else {
				onToast(getString(R.string.expand_edit_forward_must));
			}
		} else if (fromType.equals(AppContext.REPLY_INFOEX)) { // 回应资料交换
																// 包含了：回应资料交换、发起资料交换两个功能。
			replyInfoex();
		} else if (fromType.equals(AppContext.APPLY_PICEX)) { // 发起照片交换
			if (!hasImage) {
				onToast(getString(R.string.expand_edit_pic_must));
				return;
			}
			applyPicex();
		} else if (fromType.equals(AppContext.REPLY_PICEX)) { // 回应照片交换
																// 包含了回应照片交换、接受照片交换两个功能。
			if (reply_picex_type.equals("accept")) {
				if (!hasImage) {
					onToast(getString(R.string.expand_edit_pic_must));
					return;
				}
			}
			replyPicex();
		} else if (fromType.equals(AppContext.REPLYPIC_PICEX)) { // 回应照片交换中的照片
			replyPicPicex();
		} else if (fromType.equals(AppContext.FORWARPIC_PICEX)) { // 转发照片交换中的照片
			forwardPicPicex();
		} else if (fromType.equals(AppContext.REPLY_PHOTO)) { // 评论相册照片
			replyPhoto();
		} else if (fromType.equals(AppContext.REPLY_COMMENT)) { // 回复评论
			replyComment();
		} else if (fromType.equals(AppContext.APPLY_FRIEND)) { // 申请好友
			applyFriend();
		} else if (fromType.equals(AppContext.SEND_MESSAGE)) { // 发送私信
			sendMessage();
		} else if (fromType.equals(AppContext.ADD_ALBUM)) { // 添加相册
			addAlbum();
		} else if (fromType.equals(AppContext.EDIT_ALBUM)) { // 编辑相册
			editAlbum();
		} else if (fromType.equals(AppContext.UPLOAD_PHOTO)) { // 上传照片
			if (!hasImage) {
				onToast(getString(R.string.expand_edit_pic_must));
				return;
			}
			uploadPhoto();
		} else if (fromType.equals(AppContext.EDIT_PHOTO)) { // 编辑照片
			editPhoto();
		} else if (fromType.equals(AppContext.EDIT_MEMO)) { // 编辑备注
			editMemo();
		} else if (fromType.equals(AppContext.SET_DOING)) { // 编辑心情
			setDoing();
		} else if (fromType.equals(AppContext.FORWARD_BT)) {
			forwardBt();
		} else if (fromType.equals(AppContext.FORWARD_PHOTO)) {
			forwardPhoto();
		} else if (fromType.equals(AppContext.PAINT_BT)) {
			paintBt();
		} else if (fromType.equals(AppContext.PAINT_PICEX)) {
			paintPicex();
		} else if (fromType.equals(AppContext.PAINT_PHOTO)) {
			paintPhoto();
		}
	}

	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case send_bt:
			sendBt();
			break;
		case init_loginuser_info:
			getLoginUserInfo();
			break;
		case locate:
			locate();
			handler.sendEmptyMessage(locate);
			break;
		case replay_bt:
			replay_bt();
			break;
		case copy_mauaul_bt:
			copymanual_bt();
			break;
		case transmit_bt:
			transmitBt();
			break;
		case reply_infoex:
			replyInfoex();
			break;
		case reply_picex:
			replyPicex();
			break;
		case apply_picex:
			applyPicex();
			break;
		case replypic_picex:
			replyPicPicex();
			break;
		case forwardpic_picex:
			forwardPicPicex();
			break;
		case reply_photo:
			replyPhoto();
			break;
		case reply_comment:
			replyComment();
			break;
		case apply_friend:
			applyFriend();
			break;
		case send_message:
			sendMessage();
			break;
		case add_album:
			addAlbum();
			break;
		case edit_album:
			editAlbum();
			break;
		case upload_photo:
			uploadPhoto();
			break;
		case edit_photo:
			editPhoto();
			break;
		case edit_memo:
			editMemo();
			break;
		case set_doing:
			setDoing();
			break;
		case forward_bt:
			forwardBt();
			break;
		case forward_photo:
			forwardPhoto();
			break;
		case paint_bt:
			paintBt();
			break;
		case paint_picex:
			paintPicex();
			break;
		case paint_photo:
			paintPhoto();
			break;
		case oauth_douban:
			isGoOAuth = true;
			platform = PlatformBindConfig.Douban;
			oauth = new OAuth(this, handler, platform, PlatformBindConfig.Douban_AppKey,
					PlatformBindConfig.Douban_AppSecret);
			oauth.requestAccessToken(CALLBACKURL, PlatformBindConfig.Douban_Request_Token,
					PlatformBindConfig.Douban_Access_Token, PlatformBindConfig.Douban_Authorize);
			break;
		case oauth_facebook:
			PlatformAccount account = (PlatformAccount) obj;
			checkBind(account);
			break;
		case oauth_qq:
			isGoOAuth = true;
			platform = PlatformBindConfig.QQ;
			oauth = new OAuth(this, handler, platform);
			oauth.requestAccessTokenForOAuth2(PlatformBindConfig.QQ_Authorize);
			break;
		case oauth_renren:
			isGoOAuth = true;
			platform = PlatformBindConfig.Renren;
			oauth = new OAuth(this, handler, platform);
			oauth.requestAccessTokenForOAuth2(PlatformBindConfig.Renren_Authorize);
			break;
		case oauth_tencent:
			isGoOAuth = true;
			platform = PlatformBindConfig.Tencent;
			oauth = new OAuth(this, handler, platform);
			oauth.requestAccessTokenForOAuth2(PlatformBindConfig.Tencent_Authorize_2);
			break;
		case oauth_tritter:
			isGoOAuth = true;
			platform = PlatformBindConfig.Twitter;
			oauth = new OAuth(this, handler, PlatformBindConfig.Twitter,
					PlatformBindConfig.Twitter_ConsumerKey, PlatformBindConfig.Twitter_ConsumerSecret);
			oauth.requestAcccessTokenForTwitter();
			break;
		case oauth_weibo:
			isGoOAuth = true;
			platform = PlatformBindConfig.Sina;
			oauth = new OAuth(this, handler, platform);
			oauth.requestAccessTokenForOAuth2(PlatformBindConfig.Sina_Authorize2);
			break;
		default:
			break;
		}
	}

	private void paintPhoto() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.PAINT_PHOTO);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		paramsMap.put("picid", String.valueOf(picid));
		
		if (bind_twitter) {
			paramsMap.put("fw_twitter", "1");
		}
		if (bind_facebook) {
			paramsMap.put("fw_facebook", "1");
		}
		if (bind_douban) {
			paramsMap.put("fw_douban", "1");
		}
		if (bind_qq) {
			paramsMap.put("fw_qq", "1");
		}
		if (bind_renren) {
			paramsMap.put("fw_renren", "1");
		}
		if (bind_weibo) {
			paramsMap.put("fw_sina", "1");
		}
		if (bind_tencent) {
			paramsMap.put("fw_tqq", "1");
		}
		try {
			locateParams(paramsMap);
			SubmitTask st = new SubmitTask(this, handler, paramsMap, picFile);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void paintPicex() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.PAINT_PICEX);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		paramsMap.put("ouid", String.valueOf(ouid));
		paramsMap.put("picid", String.valueOf(picid));
		
		if (bind_twitter) {
			paramsMap.put("fw_twitter", "1");
		}
		if (bind_facebook) {
			paramsMap.put("fw_facebook", "1");
		}
		if (bind_douban) {
			paramsMap.put("fw_douban", "1");
		}
		if (bind_qq) {
			paramsMap.put("fw_qq", "1");
		}
		if (bind_renren) {
			paramsMap.put("fw_renren", "1");
		}
		if (bind_weibo) {
			paramsMap.put("fw_sina", "1");
		}
		if (bind_tencent) {
			paramsMap.put("fw_tqq", "1");
		}
		try {
			locateParams(paramsMap);
			SubmitTask st = new SubmitTask(this, handler, paramsMap, picFile);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void paintBt() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.PAINT_BT);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		paramsMap.put("btid", String.valueOf(bttype_id));
		
		if (bind_twitter) {
			paramsMap.put("fw_twitter", "1");
		}
		if (bind_facebook) {
			paramsMap.put("fw_facebook", "1");
		}
		if (bind_douban) {
			paramsMap.put("fw_douban", "1");
		}
		if (bind_qq) {
			paramsMap.put("fw_qq", "1");
		}
		if (bind_renren) {
			paramsMap.put("fw_renren", "1");
		}
		if (bind_weibo) {
			paramsMap.put("fw_sina", "1");
		}
		if (bind_tencent) {
			paramsMap.put("fw_tqq", "1");
		}
		
		try {
			locateParams(paramsMap);
			SubmitTask st = new SubmitTask(this, handler, paramsMap, picFile);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	private void forwardPhoto() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.FORWARD_PHOTO);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		if (bind_twitter) {
			paramsMap.put("fw_twitter", "1");
		}
		if (bind_facebook) {
			paramsMap.put("fw_facebook", "1");
		}
		if (bind_douban) {
			paramsMap.put("fw_douban", "1");
		}
		if (bind_qq) {
			paramsMap.put("fw_qq", "1");
		}
		if (bind_renren) {
			paramsMap.put("fw_renren", "1");
		}
		if (bind_weibo) {
			paramsMap.put("fw_sina", "1");
		}
		if (bind_tencent) {
			paramsMap.put("fw_tqq", "1");
		}
		paramsMap.put("picid", String.valueOf(picid));
		try {
			SubmitTask st = new SubmitTask(this, handler, paramsMap);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	private void forwardBt() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.FORWARD_BT);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		paramsMap.put("btid", String.valueOf(bttype_id));
		paramsMap.put("fuids", String.valueOf(fuids));
		try {
			SubmitTask st = new SubmitTask(this, handler, paramsMap);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (isGoOAuth) {
//			initPlatform();
			isGoOAuth = false;
			AppContext.getInstance().setOAUTH_TYPE(-1);
			UICore.eventTask(this, this, init_loginuser_info, "get_logininfo", null);
		}
	}

	private void initPlatform() {
		int type = AppContext.getInstance().getOAUTH_TYPE();
		System.out.println("open_type:" + type);
		if (type == 0) {
			bind_qq = true;
			qqView.setBackgroundResource(R.drawable.edit_ico_qq);
		} else if (type == 1) {
			bind_weibo = true;
			weiboView.setBackgroundResource(R.drawable.edit_ico_weibo);
		} else if (type == 2) {
			bind_tencent = true;
			tentcentView.setBackgroundResource(R.drawable.edit_ico_tqq);
		} else if (type == 3) {
			bind_renren = true;
			renrenView.setBackgroundResource(R.drawable.edit_ico_renren);
		} else if (type == 4) {
			bind_douban = true;
			doubanView.setBackgroundResource(R.drawable.edit_ico_douban);
		} else if (type == 5) {
			bind_twitter = true;
			twitterView.setBackgroundResource(R.drawable.edit_ico_twitter);
		} else if (type == 6) {
			bind_facebook = true;
			facebookView.setBackgroundResource(R.drawable.edit_ico_facebook);
		}
	}

	private void doPickPhotoAction() {
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
		String cancel = getString(R.string.bt_title_back);
		String[] choices;
		choices = new String[2];
		choices[0] = getString(R.string.expand_edit_take_photo); // 拍照
		choices[1] = getString(R.string.expand_edit_choose_photo); // 从相册中选择
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
		builder.setTitle(R.string.expand_edit_photo_title);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0:
							String status = Environment.getExternalStorageState();
							if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
								doTakePhoto();// 用户点击了从照相机获取
							}
							break;
						case 1:
							doCropPhoto();// 从相册中去获取
							break;
						}
					}
				});
		builder.setNegativeButton(cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}

				});
		builder.create().show();
	}

	/**
	 * 拍照获取图片
	 * 
	 */
	protected void doTakePhoto() {
		try {
			File uploadFileDir = new File(Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
			Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			if (!uploadFileDir.exists()) {
				uploadFileDir.mkdirs();
			}
			picFile = new File(uploadFileDir, "upload.jpeg");
			if (!picFile.exists()) {
				picFile.createNewFile();
			}
			photoUri = Uri.fromFile(picFile);
			cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
			startActivityForResult(cameraIntent, activity_result_camara_with_data);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 从本地手机中选择图片
	 */
	public void doSelectImageFromLoacal() {
		Intent localIntent = new Intent();
		localIntent.setType("image/*");
		localIntent.setAction("android.intent.action.GET_CONTENT");
		Intent localIntent2 = Intent.createChooser(localIntent, getString(R.string.expand_edit_choose_photo));
		startActivityForResult(localIntent2, activity_result_pick_with_data);
	}

	// 封装请求Gallery的intent
//	public Intent getPhotoPickIntent() {
//		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
//		intent.setType("image/*");
//		intent.putExtra("crop", "true");
//		intent.putExtra("aspectX", 1);
//		intent.putExtra("aspectY", 1);
//		intent.putExtra("outputX", 480);
//		intent.putExtra("outputY", 480);
//		intent.putExtra("noFaceDetection", "true");
//		intent.putExtra("scaleUpIfNeeded", "true");
//		intent.putExtra("return-data", true);
//		return intent;
//	}

	// 请求Gallery程序
//	protected void doPickPhotoFromGallery() {
//		try {
//			// Launch picker to choose photo for selected contact
//			final Intent intent = getPhotoPickIntent();
//			startActivityForResult(intent, activity_result_pick_with_data);
//		} catch (ActivityNotFoundException e) {
//			e.printStackTrace();
//		}
//	}

	protected void doCropPhoto() {
		try {
			File pictureFileDir = new File(Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
			if (!pictureFileDir.exists()) {
				pictureFileDir.mkdirs();
			}
			picFile = new File(pictureFileDir, "upload.jpeg");
			if (!picFile.exists()) {
				picFile.createNewFile();
			}
			photoUri = Uri.fromFile(picFile);
			final Intent intent = getCropImageIntent();
			startActivityForResult(intent, activity_result_cropimage_with_data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Constructs an intent for image cropping. 调用图片剪辑程序
	 */
	public Intent getCropImageIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 600);
		intent.putExtra("outputY", 600);
		intent.putExtra("noFaceDetection", true);
		intent.putExtra("scale", true);
		intent.putExtra("return-data", false);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		return intent;
	}
	
	private void cropImageUriByTakePhoto() {
		 Intent intent = new Intent("com.android.camera.action.CROP");
		 intent.setDataAndType(photoUri, "image/*");
		 intent.putExtra("crop", "true");
		 intent.putExtra("aspectX", 1);
		 intent.putExtra("aspectY", 1);
		 intent.putExtra("outputX", 600);
		 intent.putExtra("outputY", 600);
		 intent.putExtra("scale", true);
		 intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
		 intent.putExtra("return-data", false);
		 intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		 intent.putExtra("noFaceDetection", true); // no face detection
		 startActivityForResult(intent, activity_result_cropimage_with_data);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case activity_result_pick_with_data: // 从本地选择图片
			if (data == null) {
				return;
			}
			Uri uri = data.getData();
			ContentResolver resolver = getContentResolver();
			try {
				InputStream inputStream1 = resolver.openInputStream(uri);
				InputStream inputStream2 = resolver.openInputStream(uri);
				Bitmap bitmapDecode = ImageThumbnail.decodeStream(inputStream1, inputStream2, REQUEST_WIDTH);
				if (bitmapDecode.getWidth() > REQUEST_WIDTH) {
					bitmapWeak = new WeakReference<Bitmap>(ImageThumbnail.getCompressBmp(bitmapDecode, REQUEST_WIDTH, true));
				} else {
					bitmapWeak = new WeakReference<Bitmap>(bitmapDecode);
				}
				File pictureFileDir = new File(
						Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
				if (!pictureFileDir.exists()) {
					pictureFileDir.mkdirs();
				}
				picFile = new File(pictureFileDir, "upload.jpeg");
				if (!picFile.exists()) {
					picFile.createNewFile();
				}
				FileOutputStream ous = new FileOutputStream(picFile);
				bitmapWeak.get().compress(Bitmap.CompressFormat.JPEG, 100, ous);
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case activity_result_camara_with_data: // 拍照
			try {
				try {
					Thread.sleep(100);	
				} catch (Exception e) {
					e.printStackTrace();
				}
				cropImageUriByTakePhoto();
//				if (picFile != null && picFile.length() > 0) {
//					InputStream inputStream1 = new FileInputStream(picFile);
//					InputStream inputStream2 = new FileInputStream(picFile);
//					Bitmap bitmapDecode = ImageThumbnail.decodeStream(inputStream1, inputStream2, REQUEST_WIDTH);
//					if (bitmapDecode.getWidth() > REQUEST_WIDTH) {
//						bitmapWeak = new WeakReference<Bitmap>(ImageThumbnail.getCompressBmp(bitmapDecode, REQUEST_WIDTH, true));
//					} else {
//						bitmapWeak = new WeakReference<Bitmap>(bitmapDecode);
//					}
//					Intent intent = new Intent(this, CropImageActivity.class);
//					intent.putExtra("path", picFile.getAbsolutePath());
//					startActivityForResult(intent, activity_result_cropimage_with_data);
//				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case activity_result_cropimage_with_data:
				try {
					if (photoUri != null) {
//						bitmapWeak = new WeakReference<Bitmap>(decodeUriAsBitmap(photoUri));
//						FileOutputStream out = new FileOutputStream(picFile);
//						if (bitmapWeak.get().compress(Bitmap.CompressFormat.JPEG, 80, out)) {
//							out.flush();
//							out.close();
//						}
						startFeather();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			break;
		case activity_result_aviary_with_data:
			try {
				if (picFile.exists()) {
					File file = Utility.getNextFileName();
					updateMedia(file.getAbsolutePath());
					if (photoUri != null) {
						Bitmap bitmap = decodeUriAsBitmap(photoUri);
						uploadpicView.setImageBitmap(bitmap);
						hasImage = true;
					}
//					if ( null != mSessionId ) {
//						processHD( mSessionId );
//					}
//					mSessionId = null;
//					InputStream in = new FileInputStream(picFile);
//					BitmapFactory.Options options1 = new BitmapFactory.Options();
//					options1.inPurgeable = true;
//					options1.inInputShareable = true;
//					options1.inSampleSize = 1;
//					try {
//						BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(options1, true);
//					} catch (Exception ex) {
//						ex.printStackTrace();
//					}
//					bitmapWeak = new WeakReference<Bitmap>(BitmapFactory.decodeStream(in, null, options1));
//					uploadpicView.setImageBitmap(bitmapWeak.get());
//					hasImage = true;
//					
//					FileOutputStream out = new FileOutputStream(picFile);
//					if (bitmapWeak.get().compress(Bitmap.CompressFormat.PNG, 50, out)) {
//						out.flush();
//						out.close();
//					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		}
	}

	
	
	/**
	 * We need to notify the MediaScanner when a new file is created. In this way all the gallery applications will be notified too.
	 * 
	 * @param file
	 */
	private void updateMedia( String filepath ) {
		Log.i( TAG, "updateMedia: " + filepath );
		MediaScannerConnection.scanFile( getApplicationContext(), new String[] { filepath }, null, null );
	}

	/**
	 * Start the hi-res image processing.
	 * 
	 */
	public void processHD( final String session_name ) {

		Log.i( TAG, "processHD: " + session_name );

		// get a new file for the hi-res file
		File destination = new File(
				Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH+"/upload/", "upload.jpeg");

		String error = null;

		// Now we need to fetch the session information from the content provider
		FeatherContentProvider.SessionsDbColumns.Session session = null;

		Uri sessionUri = FeatherContentProvider.SessionsDbColumns.getContentUri( session_name );

		// this query will return a cursor with the informations about the given session
		Cursor cursor = getContentResolver().query( sessionUri, null, null, null, null );

		if ( null != cursor ) {
			session = FeatherContentProvider.SessionsDbColumns.Session.Create( cursor );
			cursor.close();
		}

		if ( null != session ) {
			// Print out the session informations
			Log.d( TAG, "session.id: " + session.id ); // session _id
			Log.d( TAG, "session.name: " + session.session ); // session name
			Log.d( TAG, "session.ctime: " + session.ctime ); // creation time
			Log.d( TAG, "session.file_name: " + session.file_name ); // original file, it is the same you passed in the
																								// startActivityForResult Intent

			// Now, based on the session information we need to retrieve
			// the list of actions to apply to the hi-res image
			Uri actionsUri = FeatherContentProvider.ActionsDbColumns.getContentUri( session.session );

			// this query will return the list of actions performed on the original file, during the FeatherActivity session.
			// Now you can apply each action to the hi-res image to replicate the same result on the bigger image
			cursor = getContentResolver().query( actionsUri, null, null, null, null );

			if ( null != cursor ) {
				// If the cursor is valid we will start a new asynctask process to query the cursor
				// and apply all the actions in a queue
				HDAsyncTask task = new HDAsyncTask( Uri.parse( session.file_name ), destination.getAbsolutePath(), session_name );
				task.execute( cursor );
			} else {
				error = "Failed to retrieve the list of actions!";
			}
		} else {
			error = "Failed to retrieve the session informations";
		}

		if ( null != error ) {
			Toast.makeText( this, error, Toast.LENGTH_LONG ).show();
		}
	}

	/**
	 * 扔瓶子
	 */
	private void sendBt() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.SEND_BT);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		if (entry.getBttype_allow_spread() == 1) {
			if (bind_twitter) {
				paramsMap.put("fw_twitter", "1");
			} 
			if (bind_facebook) {
				paramsMap.put("fw_facebook", "1");
			}
			if (bind_douban) {
				paramsMap.put("fw_douban", "1");
			}
			if (bind_qq) {
				paramsMap.put("fw_qq", "1");
			}
			if (bind_renren) {
				paramsMap.put("fw_renren", "1");
			}
			if (bind_weibo) {
				paramsMap.put("fw_sina", "1");
			}
			if (bind_tencent) {
				paramsMap.put("fw_tqq", "1");
			}
		} 
		paramsMap.put("bttype_id", String.valueOf(bttype_id));
		if (bt_geo_lng == 0.0) {
			bt_geo_lng = AppContext.getInstance().getLongitude();
		}
		if (bt_geo_lat == 0.0) {
			bt_geo_lat = AppContext.getInstance().getLatitude();
		}
		System.out.println("expandedit: bt_geo_lat:" + bt_geo_lat + ";bt_geo_lng:" + bt_geo_lng);
		paramsMap.put("bt_geo_lng", String.valueOf(bt_geo_lng == 0.0 ? 0 : bt_geo_lng));
		paramsMap.put("bt_geo_lat", String.valueOf(bt_geo_lat == 0.0 ? 0 : bt_geo_lat));
		paramsMap.put("bt_geo_reference", bt_geo_reference == null ? "" : bt_geo_reference);
		paramsMap.put("bt_tagid", bundle.getString("bt_tagid"));
		paramsMap.put("bt_showaddress", bundle.getString("bt_showaddress"));
		paramsMap.put("bt_tag", bundle.getString("bt_tag"));
		if (bundle.containsKey("bt_samecity")) {
			paramsMap.put("bt_samecity", String.valueOf(bundle.getInt("bt_samecity")));
		}
		if (bundle.containsKey("bt_samearea")) {
			paramsMap.put("bt_samearea", String.valueOf(bundle.getInt("bt_samearea")));
		}
		if (bundle.containsKey("bt_sex")) {
			paramsMap.put("bt_sex", String.valueOf(bundle.getInt("bt_sex")));
		}
		if (bundle.containsKey("bt_age")) {
			paramsMap.put("bt_age", String.valueOf(bundle.getInt("bt_age")));
		}
		if (bundle.containsKey("bt_allowpick")) {
			paramsMap.put("bt_allowpick", String.valueOf(bundle.getInt("bt_allowpick")));
		}
		if (bundle.containsKey("bt_allowspread")) {
			paramsMap.put("bt_allowspread", String.valueOf(bundle.getInt("bt_allowspread")));
		}
		if (bundle.containsKey("bt_showreply")) {
			paramsMap.put("bt_showreply", String.valueOf(bundle.getInt("bt_showreply")));
		}
		if (bundle.containsKey("bt_showfeed")) {
			paramsMap.put("bt_showfeed", String.valueOf(bundle.getInt("bt_showfeed")));
		}
		if (bundle.containsKey("bt_fuids")) {
			paramsMap.put("bt_fuids", String.valueOf(bundle.getString("bt_fuids")));
		}
		try {
			SubmitTask st = null;
			if (hasImage) {
				st = new SubmitTask(this, handler, paramsMap, picFile);
				st.execute();
			} else {
				st = new SubmitTask(this, handler, paramsMap);
				st.execute();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 回应瓶子
	private void replay_bt() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.REPLY_BT);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		paramsMap.put("btid", String.valueOf(bttype_id));
		try {
			locateParams(paramsMap);
			SubmitTask st = null;
			if (hasImage) {
				st = new SubmitTask(this, handler, paramsMap, picFile);
				st.execute();
			} else {
				st = new SubmitTask(this, handler, paramsMap);
				st.execute();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 手动传递瓶子
	private void copymanual_bt() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.COPYMANUAL_BT);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		paramsMap.put("btid", String.valueOf(bttype_id));
		try {
			SubmitTask st = new SubmitTask(this, handler, paramsMap);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 转发瓶子
	private void transmitBt() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.TRANSMIT_BT);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		if (bind_twitter) {
			paramsMap.put("fw_twitter", "1");
		}
		if (bind_facebook) {
			paramsMap.put("fw_facebook", "1");
		}
		if (bind_douban) {
			paramsMap.put("fw_douban", "1");
		}
		if (bind_qq) {
			paramsMap.put("fw_qq", "1");
		}
		if (bind_renren) {
			paramsMap.put("fw_renren", "1");
		}
		if (bind_weibo) {
			paramsMap.put("fw_sina", "1");
		}
		if (bind_tencent) {
			paramsMap.put("fw_tqq", "1");
		}
		paramsMap.put("btid", String.valueOf(bttype_id));
		try {
			SubmitTask st = new SubmitTask(this, handler, paramsMap);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 回复交换资料
	private void replyInfoex() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.REPLY_INFOEX);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		paramsMap.put("ouid", String.valueOf(ouid));
		try {
			SubmitTask st = new SubmitTask(this, handler, paramsMap);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 发起照片交换
	private void applyPicex() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.APPLY_PICEX);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		paramsMap.put("ouid", String.valueOf(ouid));
		try {
			SubmitTask st = new SubmitTask(this, handler, paramsMap, picFile);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 回应照片交换、接受照片交换
	private void replyPicex() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.REPLY_PICEX);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		paramsMap.put("ouid", String.valueOf(ouid));
		
		try {
			locateParams(paramsMap);
			SubmitTask st = null;
			if (reply_picex_type.equals("apply")) {
				st = new SubmitTask(this, handler, paramsMap, picFile);
				st.execute();
			} else {
				if (hasImage) {
					st = new SubmitTask(this, handler, paramsMap, picFile);
					st.execute();
				} else {
					st = new SubmitTask(this, handler, paramsMap);
					st.execute();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 回应照片交换中的照片
	private void replyPicPicex() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.REPLYPIC_PICEX);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		paramsMap.put("ouid", String.valueOf(ouid));
		paramsMap.put("picid", String.valueOf(picid));
		try {
			locateParams(paramsMap);
			SubmitTask st = new SubmitTask(this, handler, paramsMap);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 转发照片交换中的照片
	private void forwardPicPicex() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.FORWARPIC_PICEX);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		paramsMap.put("picid", String.valueOf(picid));
		paramsMap.put("pic_uid", String.valueOf(pic_uid));
		paramsMap.put("fuid", String.valueOf(fuid));
		try {
			locateParams(paramsMap);
			SubmitTask st = new SubmitTask(this, handler, paramsMap);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 评论相册照片
	private void replyPhoto() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.REPLY_PHOTO);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		paramsMap.put("picid", String.valueOf(picid));
		try {
			locateParams(paramsMap);
			SubmitTask st = new SubmitTask(this, handler, paramsMap);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 评论相册照片
	private void replyComment() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.REPLY_COMMENT);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		paramsMap.put("commentid", String.valueOf(commentid));
		try {
			locateParams(paramsMap);
			SubmitTask st = new SubmitTask(this, handler, paramsMap);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 申请好友
	private void applyFriend() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.APPLY_FRIEND);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		paramsMap.put("ouid", String.valueOf(ouid));
		try {
			locateParams(paramsMap);
			SubmitTask st = new SubmitTask(this, handler, paramsMap);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 发送私信
	private void sendMessage() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.SEND_MESSAGE);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		paramsMap.put("ouid", String.valueOf(ouid));
		try {
			locateParams(paramsMap);
			SubmitTask st = new SubmitTask(this, handler, paramsMap);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 添加相册
	private void addAlbum() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.ADD_ALBUM);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		try {
			SubmitTask st = new SubmitTask(this, handler, paramsMap);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 编辑相册
	private void editAlbum() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.EDIT_ALBUM);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		paramsMap.put("albumid", String.valueOf(albumid));
		try {
			SubmitTask st = new SubmitTask(this, handler, paramsMap);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 上传照片
	private void uploadPhoto() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.UPLOAD_PHOTO);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		paramsMap.put("albumid", String.valueOf(albumid));
		try {
			locateParams(paramsMap);
			SubmitTask st = new SubmitTask(this, handler, paramsMap, picFile);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 编辑照片
	private void editPhoto() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.EDIT_PHOTO);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		paramsMap.put("picid", String.valueOf(picid));
		try {
			SubmitTask st = new SubmitTask(this, handler, paramsMap);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 设置备注
	private void editMemo() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.EDIT_MEMO);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		paramsMap.put("ouid", String.valueOf(ouid));
		try {
			SubmitTask st = new SubmitTask(this, handler, paramsMap);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 设置心情
	private void setDoing() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("form_type", AppContext.SET_DOING);
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("message", editView.getText().toString().trim());
		try {
			SubmitTask st = new SubmitTask(this, handler, paramsMap);
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void locateParams(HashMap<String, String> paramsMap) {
		if (isLocate) {
			if (myLocation != null) {
				paramsMap.put("geo_lng", String.valueOf(myLocation.getLongitude()));
				paramsMap.put("geo_lat", String.valueOf(myLocation.getLatitude()));
				paramsMap.put("geo_country", myLocation.getCountry());
				paramsMap.put("geo_city", myLocation.getCity());
				paramsMap.put("geo_area", myLocation.getArea());
				paramsMap.put("geo_location", myLocation.getAddress());
			}
		}
	}

	private void locate() {
		myLocation = new LocationEntry();
		myLocation.setLatitude(AppContext.getInstance().getLatitude());
		myLocation.setLongitude(AppContext.getInstance().getLongitude());
		String params = String.valueOf(AppContext.getInstance().getLatitude()) + "," + String.valueOf(AppContext.getInstance().getLongitude());
		String language = AppContext.language == 1 ? "zh" : "en";
		String url = "http://www.mobibottle.com/openapi/geocode_offset.json?" +
				"latlng="+params+"&sensor=true&language=" + language + "&login_uid=" + AppContext.getInstance().getLogin_uid();
		try {
			String result = HttpUtils.doGet(url);
			JSONObject object = new JSONObject(result);
			JSONArray arrays = object.getJSONArray("results");
			for (int i = 0; i < arrays.length(); i++) {
				JSONObject jsonObject = arrays.getJSONObject(i);
				if (jsonObject != null) {
					JSONArray addressArrays = jsonObject.getJSONArray("address_components");
					for (int j = 0; j < addressArrays.length(); j++) {
						JSONObject obj = addressArrays.getJSONObject(j);
						JSONArray typeArray = obj.getJSONArray("types");
						for (int k = 0; k < typeArray.length(); k++) {
							String typename = typeArray.getString(k);
							if (typename.equals("locality")) {
								myLocation.setCity(obj.getString("long_name"));
							} else if (typename.equals("administrative_area_level_1")) {
								myLocation.setProvince(obj.getString("long_name"));
							} else if (typename.equals("country")) {
								myLocation.setCountry(obj.getString("long_name"));
							}
						}
					}
					myLocation.setAddress(jsonObject.getString("formatted_address"));
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	private void getLoginUserInfo() {
		StringBuffer url = new StringBuffer(UrlConfig.get_loginuser_info);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());

		try {
			String result = HttpUtils.doGet(url.toString());
			if (result == null) {
				return;
			}
			Gson gson = new Gson();
			LoginUserInfo loginUserInfo = gson.fromJson(result, LoginUserInfo.class);
			LoginUserInfoTable loginUserInfoTable = new LoginUserInfoTable();
			if (null != loginUserInfoTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid())) {
				loginUserInfoTable.deleteLoginUserInfoById(AppContext.getInstance().getLogin_uid());
				loginUserInfoTable.saveLoginUserInfo(loginUserInfo.getLoginuser_info(), AppContext.getInstance().getLogin_uid());
			} else {
				loginUserInfoTable.saveLoginUserInfo(loginUserInfo.getLoginuser_info(), AppContext.getInstance().getLogin_uid());
			}
			userEntry = loginUserInfoTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			AppContext.getInstance().setFromExchangeTime(false);
			AppContext.getInstance().setFromExchangeTimeToChangeFriend(false);
			AppContext.getInstance().setFromBottleTime(false);
		}
		return super.onKeyUp(keyCode, event);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			if (OAuth.reciver != null) {
				unregisterReceiver(OAuth.reciver);
			}
			File uploadFileDir = new File(Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
			File file = new File(uploadFileDir, "upload.jpeg");
			if (file.exists()) {
				file.delete();
			}
			if (bitmapWeak != null && !bitmapWeak.get().isRecycled()) {
				bitmapWeak.get().recycle();
				bitmapWeak = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		try {
			switch (msg.what) {
			case send_bt_error:
				onToast((String) msg.obj);
				break;
			case send_bt_success:
				Object[] objs = (Object[]) msg.obj;
				onToast((String) objs[0]);
				Intent intent = new Intent(ExpandEditActivity.this, BottleTipsActivity.class);
				intent.putExtra("type", "throw");
				intent.putExtra("bottleId", Integer.parseInt(objs[1].toString()) == 0 ? bttype_id : Integer.parseInt(objs[1].toString()));
				intent.putExtra("gainbt_msg", objs[2].toString());
				startActivity(intent);
				break;
			case locate:
				if (myLocation != null && myLocation.getAddress() != null) {
					isLocate = true;
					locateView.setBackgroundResource(R.drawable.locate_blue);
					locationView.setText(myLocation.getAddress());
				} 
				break;
			case do_success:
				onToast((String) msg.obj);
				if (fromType.equals(AppContext.REPLY_BT)
						|| fromType.equals(AppContext.COPYMANUAL_BT)
						|| fromType.equals(AppContext.TRANSMIT_BT)) {
					if (AppContext.getInstance().isFromBottleTime()) {
						if (isNeedUpdate) {
							finish();
						} else {
							AppContext.getInstance().setFromBottleTime(false);
							finish();
						}
					} else if (!TextUtils.isEmpty(return_type) && return_type.equals(BottleSingleActivity.class.getSimpleName())) {
						Intent successIntent = new Intent(ExpandEditActivity.this, BottleSingleActivity.class);
						successIntent.putExtra("need_refresh", isNeedUpdate);
						setResult(0, successIntent);
					} else {
						Intent successIntent = new Intent(ExpandEditActivity.this, BottleDetailActivity.class);
						successIntent.putExtra("need_refresh", isNeedUpdate);
						setResult(0, successIntent);
					}
					// successIntent.putExtra("need_refresh", true);
					// successIntent.putExtra("btid",bttype_id);
					// successIntent.putExtra("type", 1);
				} else if (fromType.equals(AppContext.REPLY_INFOEX)) {
						Intent successIntent = new Intent(ExpandEditActivity.this, ExchangeInfoDetailActivity.class);
						successIntent.putExtra("ouid", ouid);
						startActivity(successIntent);
				} else if (fromType.equals(AppContext.REPLY_PICEX)) {
					if (AppContext.getInstance().isFromExchangeTime()) {
						if (isNeedUpdate) {
							finish();
						} else {
							AppContext.getInstance().setFromExchangeTime(false);
							finish();
						}
					} else if (AppContext.getInstance().isFromExchangeTimeToChangeFriend()) {
						if (isNeedUpdate) {
							AppContext.getInstance().setCurrentItem(0);
							finish();
						} else {
							AppContext.getInstance().setFromExchangeTimeToChangeFriend(false);
							finish();
						}
					} else {
						Intent successIntent = new Intent(ExpandEditActivity.this, ExchangePicDetailActivity.class);
						successIntent.putExtra("need_refresh", isNeedUpdate);
						setResult(0, successIntent);
					}
				} else if (fromType.equals(AppContext.APPLY_PICEX)) {
						Intent successIntent = new Intent(ExpandEditActivity.this, ExchangePicDetailActivity.class);
						successIntent.putExtra("ouid", ouid);
						startActivity(successIntent);
				} else if (fromType.equals(AppContext.REPLYPIC_PICEX)
						|| fromType.equals(AppContext.FORWARPIC_PICEX)) {
					if (AppContext.getInstance().isFromExchangeTime()) {
						if (isNeedUpdate) {
							finish();
						} else {
							AppContext.getInstance().setFromExchangeTime(false);
							finish();
						}

					}  else if (AppContext.getInstance().isFromExchangePicDetail()) {
						if (isNeedUpdate) {
							finish();
						} else {
							AppContext.getInstance().setFromExchangePicDetail(false);
							finish();
						}
					} else if (!TextUtils.isEmpty(return_type) && return_type.equals(ExchangePicDetailActivity.class.getSimpleName())) {
						AppContext.getInstance().setFromExchangePicSession(true);
					} else {
						Intent successIntent = new Intent(ExpandEditActivity.this, ExchangePicFeedDetailActivity.class);
						successIntent.putExtra("need_refresh", isNeedUpdate);
						setResult(0, successIntent);	
					}
				} else if (fromType.equals(AppContext.REPLY_PHOTO)
						|| fromType.equals(AppContext.EDIT_PHOTO)) {
					Intent successIntent = new Intent(ExpandEditActivity.this, UserPhotoActivity.class);
					setResult(RESULT_OK, successIntent);
				} else if (fromType.equals(AppContext.FORWARD_PHOTO)) {
					if (return_type != null && return_type.equals(ExchangePicDetailActivity.class.getSimpleName())) {
						AppContext.getInstance().setFromExchangePicSession(true);
					} else {
						Intent successIntent = new Intent(ExpandEditActivity.this, UserPhotoActivity.class);
						setResult(RESULT_OK, successIntent);
					}
				}else if (fromType.equals(AppContext.SEND_MESSAGE)) {
					Intent intentMessage = new Intent(ExpandEditActivity.this, ConversationListActivity.class);
					intentMessage.putExtra("ouid", ouid);
					startActivity(intentMessage);
				} else if (fromType.equals(AppContext.SET_DOING)) {
					Intent intentSetting = new Intent(ExpandEditActivity.this, SettingActivity.class);
					startActivity(intentSetting);
				} else if (fromType.equals(AppContext.ADD_ALBUM)) {
					Intent successIntent = new Intent(ExpandEditActivity.this, AlbumsActivity.class);
					setResult(RESULT_OK, successIntent);
				} else if (fromType.equals(AppContext.EDIT_ALBUM)) {
					if (album_from != null && album_from.equals("album")) {
						Intent successIntent = new Intent(ExpandEditActivity.this, AlbumsActivity.class);
						setResult(RESULT_OK, successIntent);
					} else {
						Intent successIntent = new Intent(ExpandEditActivity.this, PhotosActivity.class);
						setResult(RESULT_OK, successIntent);
					}
				} else if (fromType.equals(AppContext.UPLOAD_PHOTO)) {
					if (upload_from != null) {
						if (upload_from.equals("album")) {
							Intent successIntent = new Intent(ExpandEditActivity.this, AlbumsActivity.class);
							setResult(RESULT_OK, successIntent);
						} else if (upload_from.equals("photos")) {
							Intent successIntent = new Intent(ExpandEditActivity.this, PhotosActivity.class);
							setResult(RESULT_OK, successIntent);
						} else if (upload_from.equals("photo_detail")) {
							Intent successIntent = new Intent(ExpandEditActivity.this, PhotosActivity.class);
							successIntent.putExtra("albumid", albumid);
							successIntent.putExtra("ouid", ouid);
							startActivity(successIntent);
						} else {
							Intent successIntent = new Intent(ExpandEditActivity.this, AlbumsActivity.class);
							successIntent.putExtra("ouid", ouid);
							startActivity(successIntent);
						}
					} else {
						Intent successIntent = new Intent(ExpandEditActivity.this, AlbumsActivity.class);
						successIntent.putExtra("ouid", ouid);
						startActivity(successIntent);
					}
				} else if (fromType.equals(AppContext.REPLY_COMMENT)) {
					if (return_type != null && return_type.equals(UserPhotoActivity.class.getSimpleName())) {
						Intent successIntent = new Intent(ExpandEditActivity.this, UserPhotoActivity.class);
						successIntent.putExtra("need_refresh", isNeedUpdate);
						setResult(RESULT_OK, successIntent);
					} else if (return_type.equals("bottledetailactivity")) {
						Intent successIntent = new Intent(ExpandEditActivity.this, BottleDetailActivity.class);
						successIntent.putExtra("need_refresh", isNeedUpdate);
						setResult(0, successIntent);
					}
				
				} else if (fromType.equals(AppContext.PAINT_BT)) {
					if (return_type != null && return_type.equals(BottleDetailActivity.class.getSimpleName())) {
						AppContext.getInstance().setBottleDetailActNeedRefresh(true);
					} else if (return_type != null && return_type.equals(BottleFragment.class.getSimpleName())) {
						AppContext.getInstance().setFromBottleTime(true);	
					} else if (return_type != null && return_type.equals(BottleSingleActivity.class.getSimpleName())) {
						AppContext.getInstance().setFromBottleSingle(true);
					}
				} else if (fromType.equals(AppContext.PAINT_PICEX)) {
					if (return_type != null && return_type.equals(ExchangePicFeedDetailActivity.class.getSimpleName())) {
						AppContext.getInstance().setFromExchangePicDetail(true);
					} else if (return_type != null && return_type.equals(ExchangeFragment.class.getSimpleName())) {
						AppContext.getInstance().setFromExchangeTime(true);	
					} else if (return_type != null && return_type.equals(ExchangePicDetailActivity.class.getSimpleName())) {
						AppContext.getInstance().setFromExchangePicSession(true);	
					}
				} else if (fromType.equals(AppContext.PAINT_PHOTO)) {
					AppContext.getInstance().setFromUserPhotoActivity(true);	
				} else if (fromType.equals(AppContext.FORWARD_BT)) {
					if (return_type != null && return_type.equals(BottleSingleActivity.class.getSimpleName())) {
						AppContext.getInstance().setFromBottleSingle(true);
					} else if (return_type != null && return_type.equals(BottleDetailActivity.class.getSimpleName())) {
						AppContext.getInstance().setBottleDetailActNeedRefresh(true);
					} else if (return_type != null && return_type.equals(BottleFragment.class.getSimpleName())) {
						AppContext.getInstance().setFromBottleTime(true);
					}
				}
				finish();
				break;
			case error:
				onToast((String) msg.obj);
				break;
			case AppContext.oauth_bind:
				initPlatform();
				break;
			case oauth_facebook:
				PlatformAccount account = (PlatformAccount) msg.obj;
				UICore.eventTask(ExpandEditActivity.this, ExpandEditActivity.this, oauth_facebook, "", account);
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	@Override
	public void locateSuccess() {
		super.locateSuccess();
		UICore.eventTask(this, this, locate, null, null);
	}
	
	public class SampleAuthListener implements AuthListener {

		public void onAuthSucceed() {
			System.out.println("You have logged in! ");
		}

		public void onAuthFail(String error) {
			System.out.println("Login Failed: " + error);
		}
	}

	public class SampleRequestListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			try {
				PlatformAccount account = new PlatformAccount();
				Log.d("Facebook-Example", "Response: " + response.toString());
				JSONObject json = Util.parseJson(response);
				account.setAccessToken(mFacebook.getAccessToken());
				if (json.has("name")) {
					account.setNickName(json.getString("name"));
				}
				account.setOpenAvatar("https://graph.facebook.com/"+json.getString("id")+"/picture?type=large");
				account.setOpenExpire(String.valueOf(mFacebook.getAccessExpires()));
				account.setOpenType(6);
				account.setOpenUid(json.getString("id"));
				PlatformAccountTable paTable = new PlatformAccountTable();
				paTable.save(account);
				if (account.getOpenUid() != null && !account.getOpenUid().equals("")) {
					Message msg = Message.obtain(handler, oauth_facebook, account);
					handler.sendMessage(msg);
				}
			} catch (JSONException e) {
				Log.w("Facebook-Example", "JSON Error in response");
			} catch (FacebookError e) {
				Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
			}
		}
	}

	private final class LoginDialogListener implements DialogListener {
        public void onComplete(Bundle values) {
            SessionEvents.onLoginSuccess();
        }

        public void onFacebookError(FacebookError error) {
            SessionEvents.onLoginError(error.getMessage());
        }
        
        public void onError(DialogError error) {
            SessionEvents.onLoginError(error.getMessage());
        }

        public void onCancel() {
            SessionEvents.onLoginError("Action Canceled");
        }
    }
	
	private class SessionListener implements AuthListener {
        
        public void onAuthSucceed() {
            mAsyncRunner.request("me", new SampleRequestListener());
        }
        
        public void onAuthFail(String error) {
        	
        }
    }
	
	private void checkBind(PlatformAccount account) {
		String url = UrlConfig.check_bind;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("open_type", String.valueOf(account.getOpenType()));
		paramsMap.put("access_token", account.getAccessToken());
		paramsMap.put("token_secret", account.getTokenSecret());
		paramsMap.put("nickname", account.getNickName());
		paramsMap.put("open_uid", account.getOpenUid());
		paramsMap.put("open_sex", String.valueOf(account.getOpenSex()));
		paramsMap.put("open_expire", account.getOpenExpire());
		paramsMap.put("open_avatar", account.getOpenAvatar());
		paramsMap.put("device_token", AppContext.getInstance().getDeviceId());
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			JSONObject object = new JSONObject(result);
			if (object.has("results")) {
				final JSONObject resultObj = object.getJSONObject("results");
				System.out.println(resultObj);
				int isbind = resultObj.getInt("isbind");
				if (AppContext.getInstance().getLogin_uid() != 0 &&  AppContext.getInstance().getLogin_token() != null) {
					if (isbind == 1) {
						if (account.getOpenType() > 0) {
							AppContext.getInstance().setOAUTH_TYPE(account.getOpenType());
							handler.sendEmptyMessage(AppContext.oauth_bind);
						} else {
							AppContext.getInstance().setOAUTH_TYPE(-1);
						}
					} 
				} 
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * AsyncTask for Hi-Res image processing
	 * 
	 * @author alessandro
	 * 
	 */
	private class HDAsyncTask extends AsyncTask<Cursor, Integer, MoaHD.Error> {

		Uri uri_;
		String dstPath_;
		ProgressDialog progress_;
		String session_;
		ExifInterfaceWrapper exif_;

		/**
		 * Initialize the HiRes async task
		 * 
		 * @param source
		 *           - source image file
		 * @param destination
		 *           - destination image file
		 * @param session_id
		 *           - the session id used to retrieve the list of actions
		 */
		public HDAsyncTask( Uri source, String destination, String session_id ) {
			uri_ = source;
			dstPath_ = destination;
			session_ = session_id;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progress_ = new ProgressDialog(ExpandEditActivity.this );
			progress_.setIndeterminate( true );
			progress_.setTitle( "Processing image" );
			progress_.setMessage( "Loading image..." );
			progress_.setProgressStyle( ProgressDialog.STYLE_SPINNER );
			progress_.setCancelable( false );
			progress_.show();
		}

		@Override
		protected void onProgressUpdate( Integer... values ) {
			super.onProgressUpdate( values );

			final int index = values[0];
			final int total = values[1];
			String message = "";

			if ( index == -1 )
				message = "Saving image...";
			else{
//				message = "Applying action " + ( index + 1 ) + " of " + ( total );
				message = "Saving image...";
			}

			progress_.setMessage( message );

			Log.d(TAG, index + "/" + total + ", message: " + message );
		}

		@Override
		protected Error doInBackground( Cursor... params ) {
			Cursor cursor = params[0];

			MoaHD.Error result = Error.UnknownError;

			if ( null != cursor ) {

				// Initialize the class to perform HD operations
				MoaHD moa = new MoaHD();
				
				// try to load the source image
				result = loadImage( moa );
				Log.d( TAG, "moa.load: " + result.name() );

				// if image is loaded
				if ( result == Error.NoError ) {

					final int total_actions = cursor.getCount();
					
					Log.d(TAG, "total actions: " + total_actions );

					if ( cursor.moveToFirst() ) {

						// get the total number of actions in the queue
						// we're adding also the 'load' and the 'save' action to the total count

						// now for each action in the given cursor, apply the action to
						// the MoaHD instance
						do {
							// send a progress notification to the progressbar dialog
							publishProgress( cursor.getPosition(), total_actions );

							// load the action from the current cursor
							Action action = Action.Create( cursor );
							if ( null != action ) {
								Log.d(TAG, "executing: " + action.id + "(" + action.session_id + " on " + action.ctime + ") = "
										+ action.getActions() );
								
								// apply a list of actions to the current image
								moa.applyActions( action.getActions() );
							} else {
								Log.e(TAG, "Woa, something went wrong! Invalid action returned" );
							}

							// move the cursor to next position
						} while ( cursor.moveToNext() );
					}

					// at the end of all the operations we need to save
					// the modified image to a new file
					publishProgress( -1, -1 );
					result = moa.save( dstPath_ );
					Log.d( TAG, "moa.save: " + result.name() );

					if ( result != Error.NoError ) {
						Log.e( TAG, "failed to save the image to " + dstPath_ );
					}

					// ok, now we can save the source image EXIF tags
					// to the new image
					if ( null != exif_ ) {
						saveExif( exif_, dstPath_ );
					}

				} else {
					Log.e(TAG, "Failed to load file" );
				}
				cursor.close();

				// and unload the current bitmap. Note that you *MUST* call this method to free the memory allocated with the load
				// method
				result = moa.unload();
				Log.d( TAG, "moa.unload: " + result.name() );

				// finally dispose the moahd instance
				moa.dispose();
			}

			return result;
		}

		/**
		 * Save the Exif tags to the new image
		 * 
		 * @param originalExif
		 * @param filename
		 */
		private void saveExif( ExifInterfaceWrapper originalExif, String filename ) {
			// ok, now we can save back the EXIF tags
			// to the new file
			ExifInterfaceWrapper newExif = null;
			try {
				newExif = new ExifInterfaceWrapper( dstPath_ );
			} catch ( IOException e ) {
			
				e.printStackTrace();
			}
			if ( null != newExif && null != originalExif ) {
				originalExif.copyTo( newExif );
				// this should be changed because the editor already rotate the image
				newExif.setAttribute( ExifInterfaceWrapper.TAG_ORIENTATION, "0" );
				// let's update the software tag too
				newExif.setAttribute( ExifInterfaceWrapper.TAG_SOFTWARE, "Aviary " + FeatherActivity.SDK_VERSION );
				// ...and the modification date
				newExif.setAttribute( ExifInterfaceWrapper.TAG_DATETIME, ExifInterfaceWrapper.formatDate( new Date() ) );
				try {
					newExif.saveAttributes();
				} catch ( IOException e ) {
					e.printStackTrace();
				}
			}
		}

		@Override
		protected void onPostExecute( MoaHD.Error result ) {
			super.onPostExecute( result );

			if ( progress_.getWindow() != null ) {
				progress_.dismiss();
			}

			// in case we had an error...
			if ( result != Error.NoError ) {
				Toast.makeText( ExpandEditActivity.this, "There was an error: " + result.name(), Toast.LENGTH_SHORT ).show();
				return;
			}

			// finally notify the MediaScanner of the new generated file
			updateMedia( dstPath_ );

//			// now ask the user if he want to see the saved image
//			new AlertDialog.Builder( ExpandEditActivity.this ).setTitle( "File saved" )
//					.setMessage( "File saved in " + dstPath_ + ". Do you want to see the HD file?" )
//					.setPositiveButton( android.R.string.yes, new DialogInterface.OnClickListener() {
//
//						@Override
//						public void onClick( DialogInterface dialog, int which ) {
//
//							Intent intent = new Intent( Intent.ACTION_VIEW );
//
//							String filepath = dstPath_;
//							if ( !filepath.startsWith( "file:" ) ) {
//								filepath = "file://" + filepath;
//							}
//							intent.setDataAndType( Uri.parse( filepath ), "image/jpeg" );
//							startActivity( intent );
//
//						}
//					} ).setNegativeButton( android.R.string.no, null ).show();

			// we don't need the session anymore, now we can delete it.
			Log.d( TAG, "delete session: " + session_ );
			deleteSession( session_ );
		}

		private Error loadImage( MoaHD moa ) {
			MoaHD.Error result = Error.UnknownError;
			final String srcPath = IOUtils.getRealFilePath( ExpandEditActivity.this, uri_ );
			if ( srcPath != null ) {

				// Let's try to load the EXIF tags from
				// the source image
				try {
					exif_ = new ExifInterfaceWrapper( srcPath );
				} catch ( IOException e ) {
					e.printStackTrace();
				}
				result = moa.load( srcPath );
			} else {

				if ( SystemUtils.isHoneyComb() ) {
					InputStream stream = null;
					try {
						stream = getContentResolver().openInputStream( uri_ );
					} catch ( Exception e ) {
						result = Error.FileNotFoundError;
						e.printStackTrace();
					}
					if ( stream != null ) {
						try {
							result = moa.load( stream );
						} catch ( Exception e ) {
							result = Error.DecodeError;
						}
					} else {
						Log.e( TAG, "stream is null!" );
					}
				} else {
					ParcelFileDescriptor fd = null;
					try {
						fd = getContentResolver().openFileDescriptor( uri_, "r" );
					} catch ( FileNotFoundException e ) {
						e.printStackTrace();
						result = Error.FileNotFoundError;
					}

					if ( null != fd ) {
						result = moa.load( fd.getFileDescriptor() );
					}
				}
			}
			return result;
		}
	}
	/**
	 * Delete the session and all it's actions. We do not need it anymore.<br />
	 * Note that this is optional. All old sessions are automatically removed in Feather.
	 * 
	 * @param session_id
	 */
	private void deleteSession( final String session_id ) {
		Uri uri = FeatherContentProvider.SessionsDbColumns.getContentUri( session_id );
		getContentResolver().delete( uri, null, null );
	}
	
	private Bitmap decodeUriAsBitmap(Uri uri) {
		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
		return bitmap;
	}
	
	private void startFeather() {
		if ( !Utility.isExternalStorageAvilable() ) {
			return;
		}

		if (photoUri == null) {
			new AlertDialog.Builder( this ).setTitle( android.R.string.dialog_alert_title ).setMessage( "Failed to create a new File" ).show();
			return;
		}

		Intent newIntent = new Intent(this, FeatherActivity.class);
		newIntent.putExtra("From_Type", Constants.ACTIVITY_EDIT);
		newIntent.setData(photoUri);

		newIntent.putExtra("API_KEY", Utility.API_KEY);

		newIntent.putExtra("output", photoUri);
		newIntent.putExtra(Constants.EXTRA_OUTPUT_FORMAT, Bitmap.CompressFormat.JPEG.name());
		newIntent.putExtra(Constants.EXTRA_OUTPUT_QUALITY, 100);
		newIntent.putExtra(Constants.EXTRA_TOOLS_DISABLE_VIBRATION, true);

		final DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		int max_size = Math.min(metrics.widthPixels, metrics.heightPixels);

		max_size = (int) ((double) max_size / 0.8);
		newIntent.putExtra("max-image-size", max_size);
		newIntent.putExtra("effect-enable-borders", true);
		mSessionId = StringUtils.getSha256(System.currentTimeMillis() + Utility.API_KEY);
		Log.d(TAG, "session: " + mSessionId + ", size: " + mSessionId.length());
		newIntent.putExtra("output-hires-session-id", mSessionId);
		startActivityForResult(newIntent, activity_result_aviary_with_data);
	}
}
